import DEFAULT_AVATAR from '@/assets/imgs/default-avatar.jpg';
import CommonEditor from '@/components/CommonEditor';
import { addCommentUsingPost } from '@/services/backend/commentController';
import { uploadFileUsingPost } from '@/services/backend/fileController';
import { CloseCircleFilled, PictureOutlined } from '@ant-design/icons';
import { useModel } from '@umijs/max';
import { Avatar, Button, Card, Image, Input, message, Space, Upload, UploadProps } from 'antd';
import { useState } from 'react';

interface Props {
  targetId?: number;
  type?: string,
  callback: () => void;
  parentId?: number;
  avatar?: boolean
}

const CommentCard: React.FC<Props> = (props) => {
  const { initialState } = useModel('@@initialState');
  const { currentUser } = initialState || {};
  const { targetId, callback, parentId,type='project',avatar=true } = props;
  const [commentValue, setCommentValue] = useState<string>('');
  const [imgFileInfoList, setImgFileInfoList] = useState<string[]>([]);

  /**
   * 上传图片的props
   */
  const imgProps: UploadProps = {
    beforeUpload: (file) => {
      //最多上传5张图片
      if (imgFileInfoList.length >= 5) {
        message.warning(`${file.name} 上传失败,最多上传5张图片`);
        return false;
      }
      //只允许img上传
      const isIMG = file.type === 'image/png' || file.type === 'image/jpeg';
      if (!isIMG) {
        message.error(`${file.name} is not a img file`);
      }
      return isIMG || Upload.LIST_IGNORE;
    },
    customRequest: async (options) => {
      const { file } = options;
      //上传图片
      try {
        const res = await uploadFileUsingPost({ biz: 'comment_img' }, {}, file as File);
        //存储图片的url至list
        if (res.code === 0 && res.data) {
          if (imgFileInfoList) {
            setImgFileInfoList([...imgFileInfoList, res.data]);
          } else {
            setImgFileInfoList([res.data]);
          }
        }
        console.log(imgFileInfoList);
      } catch (e: any) {
        message.error(e.message);
      }
    },
    showUploadList: false,
  };

  /**
   * 处理输入框的变化
   */
  const handleChange = (e: any) => {
    setCommentValue(e.target.value);
  };

  /**
   * 处理移除img从List中
   */
  const handleRemoveImg = (info: string) => {
    console.log('remove=>', info);
    const updatedList = imgFileInfoList.filter((item) => item !== info);
    setImgFileInfoList(updatedList);
  };

  /**
   * 表单提交
   */
  const handleSubmit = async () => {
    try {
      const res = await addCommentUsingPost({
        content: commentValue,
        type: type,
        targetId: targetId,
        parentId: parentId,
        pictures: imgFileInfoList,
      });
      if (res.code === 0) {
        message.success('发布成功');
        //删除输入框的文字与图片
        setCommentValue('');
        setImgFileInfoList([]);
        //刷新评论
        callback();
      }
    } catch (e: any) {
      message.error(e.message);
    }
  };

  return (
    <div id={'comment'}>
      <div id={'comment-inner'} className={'flex'}>
        {avatar ? (
          <div id={'comment-inner-avatar'} className={'mr-3'}>
            <Avatar src={currentUser?.avatar ?? DEFAULT_AVATAR} size={'large'} />
          </div>
        ) : (
          <></>
        )}
        <div id={'comment-inner-content'} className={'flex-1'}>
          <Card variant={'borderless'}>
            <div className={'bg-gray-100 pb-1 rounded-lg'}>
              <div>
                <Input.TextArea
                  rows={3}
                  maxLength={100}
                  placeholder={'请输入内容~'}
                  value={commentValue}
                  onChange={handleChange}
                  spellCheck={false}
                  variant={'borderless'}
                  style={{ resize: 'none' }}
                />
              </div>
              <div className={'flex flex-wrap gap-2 py-1 px-2'}>
                {imgFileInfoList.map((imgFileInfo: string) => {
                  return (
                    <div key={1} className={'relative'}>
                      <span
                        className={'cursor-pointer hover:opacity-80'}
                        style={{
                          position: 'absolute',
                          top: '-6px',
                          right: '-6px',
                          zIndex: '50',
                        }}
                        onClick={() => handleRemoveImg(imgFileInfo)}
                      >
                        <CloseCircleFilled />
                      </span>
                      <Image className={'z-0'} width={80} src={imgFileInfo} />
                    </div>
                  );
                })}
              </div>
            </div>
            <div className={'flex mt-3 justify-between items-center'}>
              <Space direction={'horizontal'} align={'baseline'} size={'large'}>
                <a>
                  <CommonEditor callback={(val) => setCommentValue(commentValue + val)} />
                </a>
                <Upload {...imgProps}>
                  <a>
                    <Space size={4}>
                      <PictureOutlined />
                      <span>图片</span>
                    </Space>
                  </a>
                </Upload>
              </Space>
              <div>
                <Button variant={'solid'} type={'primary'} shape={'round'} onClick={handleSubmit}>
                  发布
                </Button>
              </div>
            </div>
          </Card>
        </div>
      </div>
    </div>
  );
};

export default CommentCard;
